package org.example.stockdemo.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.stockdemo.entity.Stock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class SinaStockDataService {

    @Autowired
    private RestTemplate restTemplate;

    public SinaStockDataService() {
        this.restTemplate = new RestTemplate();
    }
    
    /**
     * 从新浪API获取股票数据
     * @param stockCode 股票代码
     * @return Stock对象
     */
    public Stock getStockData(String stockCode) {
        try {
            // 构造新浪API URL
            String market = stockCode.startsWith("6") ? "sh" : "sz";
            String sinaCode = market + stockCode;
            String url = "http://hq.sinajs.cn/list=" + sinaCode;

            // 添加请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            headers.add("Referer", "http://finance.sina.com.cn");
            
            HttpEntity<String> entity = new HttpEntity<>(headers);

            // 发送请求
            String response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
            
            // 解析返回数据
            if (response != null && response.contains("=")) {
                // 提取引号内的数据部分
                String data = response.substring(response.indexOf("\"") + 1, response.lastIndexOf("\""));
                String[] values = data.split(",");
                
                // 根据新浪API文档，股票数据字段如下：
                // 0: 股票名称
                // 1: 今日开盘价
                // 2: 昨日收盘价
                // 3: 当前价格
                // 4: 今日最高价
                // 5: 今日最低价
                if (values.length >= 32) {
                    Stock stock = new Stock();
                    stock.setCode(stockCode);
                    stock.setName(values[0]); // 股票名称
                    /*stock.setPrice(new BigDecimal(values[3])); // 当前价格
                    
                    // 计算涨跌幅百分比 = (当前价格 - 昨日收盘价) / 昨日收盘价 * 100
                    BigDecimal yesterdayClosingPrice = new BigDecimal(values[2]); // 昨日收盘价
                    if (yesterdayClosingPrice.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal changePercent = (new BigDecimal(values[3]).subtract(yesterdayClosingPrice))
                                .divide(yesterdayClosingPrice, 4, BigDecimal.ROUND_HALF_UP)
                                .multiply(new BigDecimal(100));
                        stock.setChangePercent(changePercent);
                    } else {
                        stock.setChangePercent(BigDecimal.ZERO);
                    }
                    
                    stock.setMarket(market.toUpperCase());*/
                    return stock;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 根据关键字搜索股票（通过新浪API）
     * @param keyword 搜索关键字
     * @return 股票列表
     */
    public List<Stock> searchStocksFromSina(String keyword) {
        List<Stock> result = new ArrayList<>();
        try {
            result.add(getStockData(keyword));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}